package com.openroom.ui;

import java.net.URL;
import java.util.List;

import javax.jws.WebParam.Mode;

import org.apache.pivot.wtk.Button;
import org.apache.pivot.wtk.ButtonPressListener;

import com.openroom.db.DBHelper;
import com.openroom.model.ModelLocator;
import com.openroom.model.ModelLocator.ModeFlag.NavigationMode;
import com.openroom.model.Photograph;
import com.openroom.ui.component.FilterPanel;

public class FilterButtonListener implements ButtonPressListener {
    URL resource = MainWindow.class.getClassLoader().getResource(
            "com/openroom/ui/green_star.png");
    URL unselected = MainWindow.class.getClassLoader().getResource(
            "com/openroom/ui/white_star.png");

    private FilterPanel panel;

    public FilterButtonListener(FilterPanel panel) {
        this.panel = panel;
    }

    @Override
    public void buttonPressed(Button button) {
        try {
            Integer value = (Integer) button.getUserData().get("RATING_VALUE");
            Integer prev_value = (Integer) button.getUserData().get(
                    "PREVIOUS_RATING_VALUE");
            if (prev_value == null) {
                button.getUserData().put("PREVIOUS_RATING_VALUE", value);
            } else {
                if (prev_value == value) {
                    button.getUserData().put("PREVIOUS_RATING_VALUE", 0);
                    value = 0;
                } else {
                    button.getUserData().put("PREVIOUS_RATING_VALUE", value);
                }
            }
            panel.changeRating(value);
            getRatedImagesOnly(value);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void getRatedImagesOnly(Integer value) {
        if (ModelLocator.getInstance().getNavigationMode()
                .equals(NavigationMode.FOLDER)) {
            getRatedImagesForFolder(value);
        } else {
            List<Photograph> allImages = DBHelper.getInstance()
                    .selectAllImagesForCatalogWithRating(
                            ModelLocator.getInstance()
                                    .getCurrentlySelectedCatalog()
                                    .getCatalogId(), value);
            ModelLocator.getInstance().setAllPhotographsOfFolder(allImages);
        }

    }

    public static void getRatedImagesForFolder(Integer value) {
        ModelLocator instance = ModelLocator.getInstance();
        int indexOf = instance.getAllFolders().indexOf(
                instance.getCurrentlySelectedFolder());
        instance.getAllFolders().get(indexOf).setLastRating(value);
        instance.getCurrentlySelectedFolder().setLastRating(value);
        List<Photograph> allImages = DBHelper.getInstance()
                .selectAllImagesForFolderWithRating(
                        instance.getCurrentlySelectedFolder().getFolderId(),
                        value);
        instance.setAllPhotographsOfFolder(allImages);
    }
}
